package com.fortune.common.spring.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fortune.util.CacheManager;
import com.fortune.vo.cache.Cache;
import com.fortune.vo.cache.TimeOut;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fortune.constants.Constants;
import com.fortune.entity.DUserInfo;
import com.fortune.entity.MUserInfo;
import com.fortune.entity.PUserInfo;

public class PermissionInterceptor extends HandlerInterceptorAdapter {
	private boolean permissionNeeded=false;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		String url = request.getServletPath();
		MUserInfo mUserInfo = (MUserInfo) session.getAttribute(Constants.SESSION_M_USER);
		DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
		PUserInfo pUserInfo = (PUserInfo) session.getAttribute(Constants.SESSION_P_USER);
		if (mUserInfo==null&&dUserInfo==null&&pUserInfo==null) {
			request.getRequestDispatcher("/error/login").forward(request, response);
			return false;
		}
		if(dUserInfo!=null) {
			String key = "cache" + "Did:" + dUserInfo.getdId();
			Cache cache = CacheManager.getCacheInfo(key);
			if (cache != null) {
				for (TimeOut timeOut : cache.getValue()) {
					if (timeOut.getId().equals(dUserInfo.getId())) {
						if (timeOut.getRandom() != dUserInfo.getRandom()) {
							request.getRequestDispatcher("/error/kickOut").forward(request, response);
							return false;
						}
						long time = timeOut.getTimeOut() + 1000 * 60 * 30;
						long t1 = System.currentTimeMillis();
						if (t1 > time) {
							request.getRequestDispatcher("/error/timeOut").forward(request, response);
							return false;
						} else {
							timeOut.setTimeOut(System.currentTimeMillis());
						}
					}
				}
			}
		}
		if (!permissionNeeded) {
			return true;
		}
		@SuppressWarnings("unchecked")
		List<String> permissions = (List<String>) session.getAttribute(Constants.SESSION_PERMISSION);
		if (permissions==null) {
			request.getRequestDispatcher("/error/permission").forward(request, response);
			return false;
		}
		for (String permission : permissions) {
			if (permission==null) {
				continue;
			}
			if (permission.indexOf(url)!=-1) {
				return true;
			}
		}
		request.getRequestDispatcher("/error/permission").forward(request, response);
		return false;
	}
	
}
